<script setup>
import {ref, watch} from "vue";
import requestUtil from "@/utils/request";
import {ElMessage} from "element-plus";

const HostGrantTreeData = ref([])
const defaultProps = {
  children: 'children',
  label: 'name',
}
const props = defineProps({
  id: {
    type: Number,
    default: -1,
    required: true
  },
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true
  },
})

const role_id = ref(0)

const formRef = ref(null)
const treeRef = ref(null)
const form = ref({
  id: -1
})

const checkStrictly = ref(false) // 默认不联动
const checkAll = ref(false) // 全选状态
const expandAll = ref(true) // 展开状态

// 全选/全不选切换
const toggleCheckAll = () => {
  if (checkAll.value) {
    treeRef.value.setCheckedNodes(HostGrantTreeData.value)
  } else {
    treeRef.value.setCheckedKeys([])
  }
}

// 展开/折叠切换
const toggleExpandAll = (value) => {
  let treeList = HostGrantTreeData.value;
  for (let i = 0; i < treeList.length; i++) {
    treeRef.value.store.nodesMap[treeList[i].id].expanded = value;
  }
}

// 获取所有节点数量
const getAllNodesCount = () => {
  let count = 0
  const countNodes = (nodes) => {
    nodes.forEach(node => {
      count++
      if (node.children && node.children.length) {
        countNodes(node.children)
      }
    })
  }
  countNodes(HostGrantTreeData.value)
  return count
}

// 监听选择变化更新全选状态
const handleCheckChange = () => {
  const checkedCount = treeRef.value.getCheckedNodes().length
  const totalCount = getAllNodesCount()
  checkAll.value = checkedCount === totalCount
}

const initFormData = async (id) => {
  const res = await requestUtil.get('role/get/hosts?id=' + id);
  treeRef.value.setCheckedKeys(res.data.msg);
  form.value.id = id
  // 初始化全选状态
  checkAll.value = treeRef.value.getCheckedNodes().length === getAllNodesCount()
}

const initTreeData = async () => {
  try {
    const res = await requestUtil.get('host/group/list?status=2')
    const data = res.data
    console.log(data)
    if (data.code === 200) {
      HostGrantTreeData.value = data.msg
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}

watch(
    () => props.dialogVisible,
    () => {
      role_id.value = props.id;
      initFormData(role_id.value);
      initTreeData();
    }
)
const emits = defineEmits(['update:modelValue'])

const handleClose = () => {
  emits('update:modelValue', false)
}

const handleConfirm = async () => {
  const checkedKeys = treeRef.value.getCheckedKeys();
  const halfCheckedKeys = treeRef.value.getHalfCheckedKeys();
  const group_list = [...checkedKeys, ...halfCheckedKeys];

  console.log(group_list, '------------group_list-')
  let res = await requestUtil.post('role/grant/host', {
    "role_id": form.value.id,
    "groups": group_list
  });
  let data = res.data;
  if (data.code === 200) {
    ElMessage.success('执行成功')
    handleClose()
  } else {
    ElMessage.error(data.msg)
  }
}


/*const handleCheck = (checkedNode, {checkedKeys}) => {
  // 处理父节点联动选中
  if (checkedNode.parent_id !== 0) {
    checkParent(checkedNode);
  }

  // 处理父节点取消逻辑
  if (!checkedKeys.includes(checkedNode.id)) {
    uncheckParent(checkedNode);
  }
};

// 递归选中父节点
const checkParent = (node) => {
  const parentNode = findParentNode(node.parent_id, HostGrantTreeData.value);
  if (parentNode) {
    // 如果父节点未选中，则强制选中
    if (!treeRef.value.getCheckedKeys().includes(parentNode.id)) {
      treeRef.value.setChecked(parentNode.id, true);
    }
    // 继续递归处理更上层父节点
    if (parentNode.parent_id !== 0) checkParent(parentNode);
  }
};

// 递归取消父节点选中状态
const uncheckParent = (node) => {
  const parentNode = findParentNode(node.parent_id, HostGrantTreeData.value);
  if (parentNode) {
    // 检查父节点是否还有其他选中子节点
    const childrenIds = parentNode.children?.map(child => child.id) || [];
    const hasCheckedChild = childrenIds.some(id => treeRef.value.getCheckedKeys().includes(id));

    if (!hasCheckedChild) {
      treeRef.value.setChecked(parentNode.id, false);
      // 继续递归处理更上层父节点
      if (parentNode.parent_id !== 0) uncheckParent(parentNode);
    }
  }
};

// 辅助函数：根据 parent_id 查找父节点
const findParentNode = (parentId, nodes) => {
  for (const node of nodes) {
    if (node.id === parentId) return node;
    if (node.children) {
      const found = findParentNode(parentId, node.children);
      if (found) return found;
    }
  }
  return null;
};*/
</script>

<template>
  <el-dialog
      :model-value="dialogVisible"
      :title="dialogTitle"
      style="padding: 40px"
      width="400px"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        label-width="100px"
    >
      <div style="margin-bottom: 15px; display: flex;">
        <el-checkbox v-model="checkStrictly">父子联动</el-checkbox>
        <el-checkbox v-model="checkAll" @change="toggleCheckAll">全选/取消全选</el-checkbox>
        <el-checkbox v-model="expandAll" @change="toggleExpandAll($event)">展开/折叠</el-checkbox>
      </div>
      <el-tree
          ref="treeRef"
          :data="HostGrantTreeData"
          :props="defaultProps"
          show-checkbox
          :default-expand-all=true
          node-key="id"
          :check-strictly="!checkStrictly"
          @check="handleCheckChange"
      />
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>